const express = require("express");
const fs = require("fs");
const path = require("path");
const router = express.Router();
const { pinyin } = require("pinyin-pro");
var xlsx = require("node-xlsx");
const { exportExcel } = require("../../utils/ExcelUtil");

//中文转拼音
router.get("/pinyin", (req, res) => {
  const { name } = req.query;
  // 转换单个汉字
  // const singlePinyin = pinyin(name, { toneType: 'none' }); // ["zhong"]
  // 转换整个句子，每个汉字生成多个拼音选项
  const multiplePinyins = pinyin(name, { toneType: "none", pattern: "mix" });
  res.json({
    name,
    pinyin: multiplePinyins,
  });
});

//流式返回文件

router.get("/stream", (req, res) => {
  // 假设我们的word文档文件就存放在这个doc目录里面
  let docxUrl = path.join(__dirname, "../../excel/Q17.pdf");

  // 允许跨域
  res.header("Access-Control-Allow-Origin", "*");

  // 设置请求头
  res.writeHead(200, {
    // 指定文件类型为pdf
    "Content-Type": "application/pdf; charset=utf-8",
    // "Content-Type": "text/markdown; charset=utf-8",
  });

  //创建可读流
  let readStream = fs.createReadStream(docxUrl);

  // 将读取的结果以管道pipe流的方式返回给前端
  readStream.pipe(res);
});

// 读取excel文件

router.get("/excel", (req, res) => {
  res.json({
    name: "excel",
    a: xlsx.parse(path.join(__dirname, "../../excel/一建统计报表.xlsx")),
  });
});

// 导出excel,调用此接口直接下载excel
router.post("/exportExcel", (req, res) => {
  console.log(req.body);
  const { outputFilename, excelData } = req.body;

  exportExcel(excelData, outputFilename);

  res.download(outputFilename, outputFilename, (err) => {
    if (err) {
      console.error("Error downloading the file:", err);
      if (!res.headersSent) {
        res.status(500).json({
          message: "Could not download the file.",
          error: err.message,
        });
      }
    } else {
      // 文件发送成功后，删除临时文件
      fs.unlink(outputFilename, (unlinkErr) => {
        if (unlinkErr) {
          console.error("Error deleting temporary file:", unlinkErr);
        } else {
          console.log("Temporary file deleted:", outputFilename);
        }
      });
    }
  });
});

module.exports = router;
